import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import router from "@/router";
import { clearLoginInfo } from "@/utils";
import company from "./company_deploy";
// 创建axios实例
const http = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // baseURL: process.env.NODE_ENV !== 'production'?'proxyApi/':process.env.VUE_APP_BASE_API,
  baseURL: company.httpUrl,
  // 超时
  timeout: 1000 * 10,
});
// request拦截器
http.interceptors.request.use(
  (config) => {
    config.data["token"] = sessionStorage.getItem("token");
    config.data.params = JSON.stringify(config.data.params);
    if (config.data.login_name && config.data.password) {
    }

    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (success_res) => {
    let res = success_res.data;
    if (res.code && res.code != 0) {
      // `token` 过期或者账号已在别处登录
      if (res.code == 70001) {
        MessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          location.href = "/#/login";
          clearLoginInfo();
          // router.push({ name: "login" });
          // store.dispatch('LogOut').then(() => {
          //   location.href = '/index';
          // })
          // location.reload(); // 强制刷新页面
          return false;
        });
      }
    }
    return res; //请求成功
  },
  (error) => {
    console.log("err" + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default http;
//
